<script setup lang="ts">
  import { computed, PropType, ref, watch } from 'vue'
  import { useOrderExport } from './services'
  import { GetOrderListParam } from '@/views/order/list/types'

  const props = defineProps({
    exportFilter: {
      type: Object as PropType<GetOrderListParam>,
      required: true,
    },
    modelValue: {
      type: Boolean,
      default: () => false,
    },
  })

  const emits = defineEmits<{
    (e: 'update:modelValue', value: boolean): void
    (e: 'close'): void
  }>()

  const {
    exportFieldList,
    customFieldList,
    sysExportFieldList,
    saveExportFieldListLoading,
    saveAndExportFieldListLoading,
    getOrderExportFieldListLoading,
    getOrderCustomFieldListLoading,
    getOrderSysExportFieldListLoading,
    getOrderCustomFieldList,
    getOrderExportFieldList,
    getOrderSysExportFieldList,
    addAllToExportFields,
    addSysFieldToExportFields,
    addCustomFieldToExportFields,
    removeAllExportField,
    removeFromExportFields,
    saveExportFieldList,
    saveAndExportFieldList,
  } = useOrderExport

  // 弹窗状态
  const visible = ref(false)

  // 拖拽的元素的索引
  const moveIndex = ref(-1)

  // 目标位置
  const targetIndex = ref(-1)

  // 工单信息的字段列表
  const orderInfoField = computed(() => {
    return sysExportFieldList.value.filter((item) => item.code.startsWith('order_'))
  })

  // 部门信息的字段列表
  const networkInfoField = computed(() => {
    return sysExportFieldList.value.filter((item) => item.code.startsWith('network_'))
  })

  // 费用信息的字段列表
  const feeInfoField = computed(() => {
    return sysExportFieldList.value.filter((item) => item.code.startsWith('fee_'))
  })

  // 公司信息的字段列表
  const customerInfoField = computed(() => {
    return sysExportFieldList.value.filter((item) => item.code.startsWith('customer_'))
  })

  // 设备信息的字段列表
  const goodInfoField = computed(() => {
    return sysExportFieldList.value.filter((item) => item.code.startsWith('good_'))
  })

  /**
   * 拖拽开始事件
   * @param {Number} index - 元素索引
   */
  const handleDragStart = (index: number) => {
    moveIndex.value = index
  }

  /**
   * 拖拽结束事件
   */
  const handleDragEnd = () => {
    const moveItem = exportFieldList.value.splice(moveIndex.value, 1)[0]
    exportFieldList.value.splice(targetIndex.value, 0, moveItem)
  }

  /**
   * 当拖动的元素进入到当前元素时触发
   * @param {Number} index - 元素索引
   */
  const handleDragEnter = (index: number) => {
    targetIndex.value = index
  }

  /**
   * 保存并导出
   */
  const handleSaveAndExportField = () => {
    saveAndExportFieldList(props.exportFilter)
  }

  const getOrderExportFieldLoading = ref(false)
  const getOrderExportField = async () => {
    getOrderExportFieldLoading.value = true
    await getOrderExportFieldList()
    await getOrderSysExportFieldList()
    await getOrderCustomFieldList()
    exportFieldList.value.forEach((column) => {
      if (column.type === 1) {
        const index = sysExportFieldList.value.findIndex((item) => item.code === column.value)
        sysExportFieldList.value.splice(index, 1)
      } else if (column.type === 2) {
        const index = customFieldList.value.findIndex((item) => item.id === column.value)
        customFieldList.value.splice(index, 1)
      }
    })
    getOrderExportFieldLoading.value = false
  }

  const onCloseDialog = () => {
    visible.value = false
    emits('update:modelValue', false)
    emits('close')
  }

  watch(
    props,
    (value) => {
      visible.value = value.modelValue
      if (visible.value) {
        getOrderExportField()
      }
    },
    { deep: true, immediate: true },
  )
</script>

<template>
  <h-drawer
    v-model="visible"
    title="工单导出"
    :width="70"
    :loading="
      getOrderCustomFieldListLoading ||
      saveAndExportFieldListLoading ||
      getOrderExportFieldListLoading ||
      getOrderSysExportFieldListLoading ||
      saveExportFieldListLoading
    "
    @close="onCloseDialog"
  >
    <div class="modal_content">
      <!-- 导出字段 -->
      <div class="export_field_container">
        <el-space>
          <div class="title">导出字段</div>
          <div class="sub_title">（拖拽可排序）</div>
          <HLink type="error" @click="removeAllExportField">清空全部</HLink>
        </el-space>
        <div class="field-list-wrapper">
          <el-space wrap :size="10">
            <div
              v-for="(field, index) in exportFieldList"
              :key="field.value"
              :draggable="true"
              class="export-field-item"
              @dragstart="handleDragStart(index)"
              @dragend="handleDragEnd"
              @dragenter="handleDragEnter(index)"
              @mouseenter="() => (field.showClose = true)"
              @mouseleave="() => (field.showClose = false)"
              @click="removeFromExportFields(field)"
            >
              <div class="export-field-item-text">{{ field.name }}</div>
              <div class="export-field-item-btn">-</div>
            </div>
          </el-space>
        </div>
      </div>

      <!-- 系统字段 -->
      <div class="system_field_container">
        <el-space>
          <div class="title">系统字段</div>
          <template v-if="sysExportFieldList.length > 0">
            <div class="sub_title">（点击添加）</div>
            <HLink type="error" @click="addAllToExportFields(1)">添加全部</HLink>
          </template>
          <div v-else class="tip">（已添加全部）</div>
        </el-space>
        <div class="order-info system-field">
          <div class="title">工单信息</div>
          <div class="content">
            <el-space wrap :size="10">
              <div
                v-for="field in orderInfoField"
                :key="field.id"
                class="add-field-item"
                @mouseenter="() => (field.showAdd = true)"
                @mouseleave="() => (field.showAdd = false)"
                @click="addSysFieldToExportFields(field)"
              >
                <div class="add-field-item-text">{{ field.name }}</div>
                <div class="add-field-item-btn">+</div>
              </div>
            </el-space>
          </div>
        </div>
        <div class="good-info system-field">
          <div class="title">设备信息</div>
          <div class="content">
            <el-space wrap :size="10">
              <div
                v-for="field in goodInfoField"
                :key="field.id"
                class="add-field-item"
                @mouseenter="() => (field.showAdd = true)"
                @mouseleave="() => (field.showAdd = false)"
                @click="addSysFieldToExportFields(field)"
              >
                <div class="add-field-item-text">{{ field.name }}</div>
                <div class="add-field-item-btn">+</div>
              </div>
            </el-space>
          </div>
        </div>
        <div class="network-info system-field">
          <div class="title">部门信息</div>
          <div class="content">
            <el-space wrap :size="10">
              <div
                v-for="field in networkInfoField"
                :key="field.id"
                class="add-field-item"
                @mouseenter="() => (field.showAdd = true)"
                @mouseleave="() => (field.showAdd = false)"
                @click="addSysFieldToExportFields(field)"
              >
                <div class="add-field-item-text">{{ field.name }}</div>
                <div class="add-field-item-btn">+</div>
              </div>
            </el-space>
          </div>
        </div>
        <div class="customer-info system-field">
          <div class="title">公司信息</div>
          <div class="content">
            <el-space wrap :size="10">
              <div
                v-for="field in customerInfoField"
                :key="field.id"
                class="add-field-item"
                @mouseenter="() => (field.showAdd = true)"
                @mouseleave="() => (field.showAdd = false)"
                @click="addSysFieldToExportFields(field)"
              >
                <div class="add-field-item-text">{{ field.name }}</div>
                <div class="add-field-item-btn">+</div>
              </div>
            </el-space>
          </div>
        </div>
        <div class="fee-info system-field">
          <div class="title">费用信息</div>
          <div class="content">
            <el-space wrap :size="10">
              <div
                v-for="field in feeInfoField"
                :key="field.id"
                class="add-field-item"
                @mouseenter="() => (field.showAdd = true)"
                @mouseleave="() => (field.showAdd = false)"
                @click="addSysFieldToExportFields(field)"
              >
                <div class="add-field-item-text">{{ field.name }}</div>
                <div class="add-field-item-btn">+</div>
              </div>
            </el-space>
          </div>
        </div>
      </div>

      <!-- 自定义字段 -->
      <div class="custom_field_container">
        <el-space>
          <div class="title">工单自定义字段</div>
          <template v-if="customFieldList.length > 0">
            <div class="sub_title">（点击添加）</div>
            <HLink type="error" @click="addAllToExportFields(2)">添加全部</HLink>
          </template>
          <div v-else class="tip">（已添加全部）</div>
        </el-space>
        <div class="field-list-wrapper">
          <el-space wrap :size="10">
            <div
              v-for="column in customFieldList"
              :key="column.id"
              class="add-field-item"
              @mouseenter="() => (column.showAdd = true)"
              @mouseleave="() => (column.showAdd = false)"
              @click="addCustomFieldToExportFields(column)"
            >
              <div class="add-field-item-text">{{ column.name }}</div>
              <div class="add-field-item-btn">+</div>
            </div>
          </el-space>
        </div>
      </div>
    </div>
    <template #footer>
      <HButton type="success" is-modal @click="handleSaveAndExportField">保存并导出</HButton>
      <HButton type="primary" is-modal @click="saveExportFieldList">保存</HButton>
      <HButton is-modal @click="onCloseDialog">取消</HButton>
    </template>
  </h-drawer>
</template>

<style scoped lang="scss">
  @import './order-export.scss';
</style>
